package logic

import (
	"api/pkg"
	"context"
	"user_srv/user"

	"api/internal/svc"
	"api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *RegisterLogic) Register(req *types.RegisterRequest) (resp *types.Response, err error) {
	//判断是否存在
	res, err := l.svcCtx.UserSrv.GetUserInfo(l.ctx, &user.GetUserInfoByUsernameRequest{Username: req.Username})
	if err != nil {
		return &types.Response{
			Code:    -1,
			Message: "服务器内部错误",
			Data:    nil,
		}, nil
	}
	if res.UserId != 0 {
		return &types.Response{
			Code:    -2,
			Message: "用户名已存在",
			Data:    nil,
		}, nil
	}
	gen := "123" //盐
	newPwd := pkg.Md5(req.Password + gen)

	_, err = l.svcCtx.UserSrv.Register(l.ctx, &user.RegisterRequest{
		Username: req.Username,
		Password: newPwd,
		Salt:     gen,
	})

	if err != nil {
		return &types.Response{
			Code:    -1,
			Message: "服务器内部错误",
			Data:    nil,
		}, nil
	}

	return &types.Response{
		Code:    0,
		Message: "注册成功",
		Data:    nil,
	}, nil
}
